const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    trainDate:'',
    selectMotions: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const trainDate = wx.getStorageSync("trainDate");
    const trainMovementsJson = wx.getStorageSync("trainMovements");
    const trainMovements = JSON.parse(trainMovementsJson) || [];
    this.setData({
      selectMotions: trainMovements,
      trainDate: trainDate
    });
  },
  bindInputStrong:function(e){
    const selectMotions = this.data.selectMotions; 
    const name = e.currentTarget.id;
    selectMotions.forEach(function(item){
      if (item.name===name){
        item.strongPercent = e.detail.value;
        }
    });
    this.setData({
      selectMotions: selectMotions
    });
  },
  bindInputRemark:function(e){
    const selectMotions = this.data.selectMotions;
    const name = e.currentTarget.id;
    selectMotions.forEach(function (item) {
      if (item.name === name) {
        item.remark = e.detail.value;
      }
    });
    this.setData({
      selectMotions: selectMotions
    });
  },
  selectMovement: function() {
    wx.navigateTo({
      url: '/pages/movementSelection/movementSelection',
    })
  },
  deleteMovement:function(e){
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除此动作？',
      success(res) {
        if (res.confirm) {
          const selectMotions = that.data.selectMotions;
          const restMotions = selectMotions.filter(item=>{
            return item.name !== e.currentTarget.id;
          });
          that.setData({
            selectMotions: restMotions
          });
        }
      }
    })
    
  },
  save:function(){
    const selectMotions = this.data.selectMotions;
    const url = app.globalData.url;
    const openId = app.globalData.openId;
    const trainDate = this.data.trainDate;
    wx.request({
      url: url + '/train/saveMovements',
      data: {
        openId: openId,
        trainDate: trainDate,
        trainMovements: selectMotions
      },
      method: 'POST',
      success: function (response) {
        if (response.data.success) {
          //保存 
          wx.navigateBack({
            delta: 1
          });
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: '保存失败:' + response.data.message,
            icon: 'none'
          })
        }
      }
    })
  }
})